import { Request, Response, NextFunction } from "express";
import jwt from 'jsonwebtoken'

const JWT_SECRET = '10D0DAC871AD017C42B994A7579E2B2F'

interface AuthRequest extends Request {
    userId?: string
}

export const authManager = (req: AuthRequest, resp: Response, next: NextFunction) => {
    const token = req.header('Authorization')?.replace('Bearer ', '')
    if (!token) {
        return resp.sendStatus(401)
    }

    try {
        const decoded: any = jwt.verify(token, JWT_SECRET)
        req.userId = decoded.userId
        next()
    } catch (error) {
        console.log('authManager cause error:', error)
        resp.sendStatus(401)
    }
}